package org.example.projecttwo.service;

import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

/**
 * 基础服务类，提供通用的服务方法
 */
@Component
public class BaseService {

    /**
     * 获取当前登录用户的ID
     * @return 当前用户ID
     */
    public Long getCurrentUserId() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof org.springframework.security.core.userdetails.User) {
            String username = ((org.springframework.security.core.userdetails.User) principal).getUsername();
            try {
                return Long.valueOf(username);
            } catch (NumberFormatException e) {
                throw new RuntimeException("当前用户ID格式错误");
            }
        }
        throw new RuntimeException("用户未登录");
    }

}